﻿var User = require("./User");
var gameDao = require("./../dao/gameDao");
var arithmetic = require("./arithmetic")
var sever = require("./sever");
var schedule = require("node-schedule");
var gameConfig = require("./../config/gameConfig");
var urlencode = require('urlencode');
var log = require("./../../util/loginfo").getInstand;

// var redis = require("redis");
// var client = redis.createClient(6379,"127.0.0.1");

var laba = require("./../../util/laba");
var redis_send_and_listen = require("./../../util/redis_send_and_listen");
//读取文件包


var GameInfo = function () {

    var _gameinfo = "";

    var Game = function () {

        //初始化算法，使用第X种
        this.initAlgorithm = function (idx) {
            log.info('####init Algorithm!####')
            log.info('use [' + idx + '] Algorithm!')
            this.A = new arithmetic(idx);
        };

        this.serverId = gameConfig.serverId;

        //初始化游戏
        this.init = function () {
            log.info('####init game!####')

            //初始化算法
            this.initAlgorithm(0);
            //初始化用户列表
            this.userList = {};
            //在线人数为0
            this.onlinePlayerCount = 0;
            //统计
            this.winTotal = 0;
            this.lotteryCount = 0;
            this.hourWinTotal = 0;
            this.hourlotteryCount = 0;

            this.score_changeLogList = [];
            this.lotteryLogList = [];
            this.lineOutList = [];

            this.bet_dict_list = [];  //下注数据

            this.history_win = [];  //历史开奖


            //维护模式
            this.maintain = false;

            this.game_type = 0;    //游戏状态   0 默认   1开始下注  2 开奖   3结束
            this.game_second = 0 //秒数

            this.sever = new sever();

            var rule = new schedule.RecurrenceRule();
            var times = [];
            for (var i = 0; i < 60; i++) {
                times.push(i);
            }
            rule.second = times;
            var c = 0;
            var self = this;
            var j = schedule.scheduleJob(rule, function () {

                if (self.maintain) {
                    --gameConfig.maintainTime;
                    //log.info(gameConfig.maintainTime);;
                    if (!gameConfig.maintainTime) {
                        self.disconnectAllUser();
                    }
                }

                var nowDate = new Date();
                var minute = nowDate.getMinutes();
                var second = nowDate.getSeconds();
                self.game_second = second;
                if (second === 0) {    //开始下注
                    log.info("开始下注  清除数组");
                    // redis_dao.init_bet_list()
                    self.bet_dict_list = [];
                    self.game_type = 1;
                    self._io.sockets.emit('BetStart', {
                        result: true,
                        type: 1,
                    });

                } else if (second === 25) {   //开奖
                    self.game_type = 2;
                    self.open_win();

                }

                if (second == 0) {
                    redis_send_and_listen.send_msg("OnlineUserMsg", {
                        server_id: gameConfig.serverId,
                        online_num: self.onlinePlayerCount
                    });
                    //log.info("推送在线人数");
                }


            });
        };

        this.lottery = function (_userId, _bet_dict_list) {
            log.info("lottery-------------------------");
            log.info(_userId);
            log.info(_bet_dict_list);
            //下注
            var bet_dict_list = _bet_dict_list;

            if (this.game_type != 1) {		//不是下注时间
                log.info("不是下注时间");
                return {code: -1};
            }
            if (!_userId) {					//传输ID错误
                log.info("未传用户ID");
                return {code: -1};
            }
            if (!this.userList[_userId]) {	//未找到用户
                log.info("找不到用户");
                return {code: -1}
            }

            var nBetSum = 0;
            //检查下注字典
            for (var i in bet_dict_list) {
                var check_bet_dict = this.A.Check_bet_dict(bet_dict_list[i]);
                if (!check_bet_dict) {
                    log.info("bet_dict缺少字段");
                    return {code: -1};
                }
                nBetSum += bet_dict_list[i].bet_gold
            }

            //用户扣钱
            var lotteryResult = this.userList[_userId].lottery(nBetSum);
            if (!lotteryResult) {
                log.info(_userId + "分数不够");
                //log.info(this.userList[_userId])
                return {code: -2}
            }
            var user_score = this.userList[_userId]._score;


            var GamblingBalanceLevelBigWin = this.A.getGamblingBalanceLevelBigWin(); //获取库存 水位 大奖幸运值
            //水位
            var nGamblingWaterLevelGold = GamblingBalanceLevelBigWin.nGamblingWaterLevelGold;


            var addBalanceGold = nBetSum * parseFloat(nGamblingWaterLevelGold / 100);    //进入库存的钱
            var addWinPool = parseInt(nBetSum - addBalanceGold);                     //进入奖池的钱
            //增加库存和奖池
            this.A.addGamblingBalanceGold(addBalanceGold, addWinPool);

            for (var ss in bet_dict_list) {
                bet_dict_list[ss]["userId"] = _userId;
                this.bet_dict_list.push(bet_dict_list[ss]);
            }
            //添加数据
            // redis_dao.save_bet(bet_dict_list)
            return {code: 2, bet_dict_list: bet_dict_list, score: user_score}

        };

        this.tt = 0;

        this.updateUserGold = function (i, userWin) {
            //判断玩家是否在线
            if (this.userList[i]) {
                var youScore = this.userList[i].getScore();
                this.userList[i].winscore(userWin);
                var youNowScore = this.userList[i].getScore();
                log.info("online open win result user " + i + " gold " + userWin + " change_type " + gameConfig.logflag);

                //记录金钱变化量
                var userInfolog = {
                    userid: i,
                    score_before: youScore,
                    score_change: userWin,
                    score_current: youNowScore,
                    change_type: gameConfig.logflag,
                    isOnline: true
                };
                this.score_changeLogList.push(userInfolog);
                
                log.info("score change list user " + i + " score_before " + youScore + " score_current " + youNowScore);
            } else {
                this._Csocket.emit("GameUpdateGold", {
                    signCode: gameConfig.LoginServeSign,
                    sendUserId: i,
                    sendCoin: userWin,
                    diamond: 0,
                    change_type: gameConfig.logflag
                });
                log.info("offline open win result user " + i + " gold " + userWin + " change_type " + gameConfig.logflag);
            }
        }

        this.open_win = function () {
            log.info("开始开奖");
            if (this.game_type != 2) {
                log.info("game_type不是2 不能开奖:" + this.game_type);
                return
            }

            //开奖
            //获取下注数据

            var redis_dict = this.bet_dict_list;
            var GamblingBalanceLevelBigWin = this.A.getGamblingBalanceLevelBigWin(); //获取库存 水位 大奖幸运值
            //奖池
            var nGamblingWinPool = GamblingBalanceLevelBigWin.nGamblingWinPool;
            //大奖幸运等级
            var nGamblingBigWinLevel = GamblingBalanceLevelBigWin.nGamblingBigWinLevel;
            //大奖幸运概率
            var nGamblingBigWinLuck = GamblingBalanceLevelBigWin.nGamblingBigWinLuck;

            var is_luck = false;
            //判断幸运值
            var random_Num_1000 = RandomNumBoth(0, 1000);
            var random_Num_100 = RandomNumBoth(0, 100);
            if (nGamblingBigWinLevel[2] >= random_Num_1000) {
                if (nGamblingBigWinLuck[2] >= random_Num_100) {
                    is_luck = true
                }
            } else if (nGamblingBigWinLevel[1] >= random_Num_1000) {
                if (nGamblingBigWinLuck[1] >= random_Num_100) {
                    is_luck = true
                }
            } else if (nGamblingBigWinLevel[0] >= random_Num_1000) {
                if (nGamblingBigWinLuck[0] >= random_Num_100) {
                    is_luck = true
                }
            }

            var dictAnalyseResults = this.A.gameProcessor(redis_dict, nGamblingWinPool, is_luck);

            var winscore = 0;
            var win_userlist = dictAnalyseResults["win_user_list"];
            //给玩家加钱
            for (var i in win_userlist) {
                var win_score = win_userlist[i];
                if (win_score) {
                    winscore += win_score;
                    this.updateUserGold(i, win_score);
                }
            }
            //减少奖池
            if (winscore > 0) {
                this.A.subGamblingBalanceGold(0, winscore)
            }
            log.info("奖池", this.A.getGamblingBalanceLevelBigWin().nGamblingWinPool);
            log.info("奖池减少", winscore);


            this.history_win.push(dictAnalyseResults["win"]);
            if (this.history_win.length > 5) {
                this.history_win.splice(0, 1)
            }

            //制作结果
            var result = {
                ResultCode: 1,
                win: dictAnalyseResults["win"],
                history_win: this.history_win,
            };
            log.info("开奖结果:", result);

            //推消息
            for (var i in this.userList) {
                var win = 0
                if (win_userlist[i]) {
                    win = win_userlist[i]
                }
                result["win_score"] = win;
                try {
                    result["user_score"] = this.userList[i]._score;
                    this.userList[i]._socket.emit('OpenWinResult', result);
                } catch (e) {

                }

            }


            //1.写记录
            var CoinLog = [];
            for (var i in win_userlist) {
                if (i <= 10000) {
                    continue;
                }
                var userInfo = {
                    userid: parseInt(i), bet: 0, lines: 0, nBetSum: 0,
                    score_before: 0, score_win: win_userlist[i],
                    score_current: 0, result_array: null,
                    score_linescore: 0, free_count_win: 0, free_count_before: 0,
                    free_count_current: 0
                };
                this.lotteryLogList.push(userInfo);

                var logTemp = {
                    userId: parseInt(i),
                    useCoin: 0,
                    winCoin: win_userlist[i],
                    tax: 0,
                    serverId: gameConfig.serverId,
                    gameId: gameConfig.gameId
                };
                CoinLog.push(logTemp);
            }
            this._Csocket.emit("insertMark", CoinLog);

            this.game_type = 3;   //状态设置为结束
            //保存奖池
            this.saveGamblingBalanceGold();
            //存日志
            this.score_changeLog();
            this.lotteryLog();

        };


        this.setIo = function (_io, _Csocket) {
            this.sever.setIo(_io, _Csocket);
            this._io = _io;
            this._Csocket = _Csocket;
        }


        this.Setmaintain = function () {
            gameConfig.maintain = true;
        }

        this.isMaintain = function () {
            return gameConfig.maintain;
        }

        //判断是否是同一scoket连续登录，不允许
        this.isLoginAgain = function (socket) {
            if (socket.userId) {
                return this.userList[socket.userId].Islogin();
            } else {
                return false;
            }
        }

        //添加用户
        this.addUser = function (_userInfo, socket) {
            this.userList[_userInfo.userid] = new User(_userInfo, socket);
        }

        this.updateUser = function (userInfo) {
            log.info("update")
            if (!this.userList[userInfo._userId]) return;

            //已经断线
            if (this.userList[userInfo._userId]._isLeave) {
                var result = {ResultCode: 0, userId: userInfo._userId};
                this._Csocket.emit("userDisconnect", result);
                delete this.userList[userInfo._userId];
                return;
            }
            this.userList[userInfo._userId].update(userInfo);

            this.LoginGame(userInfo._userId, this.serverId);
            ++this.onlinePlayerCount;

            var self = this;
            var resultObj = {
                account: self.userList[userInfo._userId]._account,
                id: self.userList[userInfo._userId]._userId,
                nickname: self.userList[userInfo._userId]._nickname,
                score: self.userList[userInfo._userId]._score,
                headimgurl: self.userList[userInfo._userId]._headimgurl,
                history_win: self.history_win
            };
            result = {resultid: '1', msg: 'login lineserver succeed!', Obj: resultObj};
            this.userList[userInfo._userId]._socket.emit('loginGameResult', result);

        }

        //获得在线人数
        this.getOnlinePlayerCount = function () {
            return this.onlinePlayerCount;
        }

        //在线所有人
        this.getOnlinePlayer = function () {
            return this.userList;
        }

        this.score_changeLog = function () {
            var self = this;
            var saveListTemp = [];
            var ItemTemp;
            var max = 0;
            if (this.score_changeLogList.length > 200) {
                max = 200;
            } else {
                max = this.score_changeLogList.length;
            }
            for (var i = 0; i < max; i++) {
                if (this.score_changeLogList.length > 0) {
                    ItemTemp = this.score_changeLogList.shift();
                    saveListTemp.push(ItemTemp);
                }
            }
            if (saveListTemp.length > 0) {
                this._Csocket.emit("score_changeLog", saveListTemp);
                //gameDao.score_changeLog(saveListTemp);
            }
        }

        this.lotteryLog = function () {
            var self = this;
            var saveListLotteryLogTemp = [];
            var ItemTemp;
            var max = 0;
            if (this.lotteryLogList.length > 200) {
                max = 200;
            } else {
                max = this.lotteryLogList.length;
            }
            for (var i = 0; i < max; i++) {
                if (this.lotteryLogList.length > 0) {
                    ItemTemp = this.lotteryLogList.shift();
                    saveListLotteryLogTemp.push(ItemTemp);
                }
            }
            if (saveListLotteryLogTemp.length > 0) {
                gameDao.lotteryLog(saveListLotteryLogTemp);
            }
        }


        //删除用户
        this.deleteUser = function (_socket) {
            if (_socket.userId) {
                //存免费次数
                var info = {
                    userId: _socket.userId,
                    freeCount: this.userList[_socket.userId].getFreeCount(),
                    LotteryCount: this.userList[_socket.userId].getLotteryCount()
                };
                gameDao.saveFree(info, function (result) {
                    if (!result)
                        log.err("存免费次数:" + _userinfo.userId + "失败!")
                });
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    serverId: gameConfig.serverId,
                    userId: _socket.userId,
                    tableId: -1,
                    seatId: -1
                });
                this.sever.LogoutRoom(this.userList[_socket.userId], _socket);
                delete this.userList[_socket.userId];
                --this.onlinePlayerCount;
            }
        }

        //删除用户
        this.deleteUserById = function (_userId, msg) {
            if (_userId) {
                var socketItem = this.userList[_userId]._socket;
                result = {resultid: 0, msg: msg};
                socketItem.emit('loginGameResult', result);
                delete this.userList[_userId];
            }
        }

        //获得用户当前分数
        this.getUserscore = function (_userId) {
            if (_userId) {
                return this.userList[_userId]._score;
            }
        }

        //获得用户
        this.getUser = function (_userId) {
            if (_userId) {
                return this.userList[_userId];
            }
        }

        //用户是否在线
        this.IsPlayerOnline = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.info("查询在线,参数错误");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                //log.info("查询在线,未找到" + _userId + "用户");
                return 1;
            } else {
                return 0;
            }
        }

        //获得用户当前分数
        this.getPlayerScore = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.info("查询分数,参数错误");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                //log.info("查询在线,未找到" + _userId + "用户");
                return this.userList[_userId].getScore();
            } else {
                return -1;
            }
        }

        //GM加分
        this.addgold = function (_userId, score) {

            if (!_userId) {					//传输ID错误
                log.info("加分,未登录")
                return 0;
            }
            if (!this.userList[_userId]) {	//未找到用户
                log.info("加分,未登录")
                return 0
            } else {
                log.info(score)
                if (this.userList[_userId].addgold(score)) {
                    log.info(this.userList[_userId].getScore())
                    log.info("加分成功!")
                    var tablestring = "table" + this.userList[_userId].getTable();
                    this._io.sockets.in(tablestring).emit('addgoldResult', {
                        userId: _userId,
                        userSeatId: this.userList[_userId].getSeat(),
                        userScore: this.userList[_userId]._score
                    })
                    return 1;
                } else {
                    log.info("减分失败,大于用户分数!");
                    return 0;
                }
            }
        }

        //保存时间段输赢状况
        this.saveSocrePool = function () {
            //获得虚拟池
            var Virtualpool = this.A.getVirtualScorePool();
            //获得实际池
            var poollist = this.A.getScorePoolList();

            //var poollistLength = this.A.getScorePoolListLength();

            var poollistId = this.A.getScoreId();

            gameDao.Update_score_pool(poollist, Virtualpool, poollistId, function (Result) {
            })
        };

        //保存库存 奖池
        this.saveGamblingBalanceGold = function () {
            //获得库存奖池
            var dict = this.A.getGamblingBalanceGold();

            gameDao.Update_GamblingBalanceGold(dict.nGamblingBalanceGold, dict.nGamblingWinPool, function (Result) {
            })
        };

        this.updateGamblingBalanceGold = function (_info) {
            log.info(_info.dataKey);
            switch (_info.dataKey) {
                case "nGamblingWaterLevelGold":
                    this.A.nGamblingWaterLevelGold = parseInt(_info.data);
                    log.info("水位:" + this.A.nGamblingWaterLevelGold);
                    break;
                case "nGamblingBalanceGold":
                    this.A.nGamblingBalanceGold = parseInt(_info.data);
                    log.info("库存:" + this.A.nGamblingBalanceGold);
                    break;
                case "nGamblingWinPool":
                    this.A.nGamblingWinPool = parseInt(_info.data);
                    log.info("奖池:" + this.A.nGamblingWinPool);
                    break;
                case "nGamblingBigWinLevel":
                    this.A.nGamblingBigWinLevel = _info.data.split(',').map(Number);
                    log.info("大奖幸运等级:" + this.A.nGamblingBigWinLevel);
                    break;
                case "nGamblingBigWinLuck":
                    this.A.nGamblingBigWinLuck = _info.data.split(',').map(Number);
                    log.info("大奖幸运概率:" + this.A.nGamblingBigWinLuck);
                    break;
                case "expectRTP":
                    this.A.expectRTP = parseInt(_info.data);
                    log.info("RTP:" + this.A.expectRTP);
                    break;
            }
        };


        //进入游戏
        this.LoginGame = function (_userId, gametype) {
            if (!this.userList[_userId]) return;
            //用户添加游戏ID
            //log.info(_userId)
            //log.info("用户进入游戏" + gametype);
            this.userList[_userId].loginGame(gametype);
        };


        //进入房间
        this.LoginRoom = function (_userId, roomid, _socket) {
            if (!this.userList[_userId]) return;


            if (!this.userList[_userId].getGameId()) {
                log.info("用户" + _userId + ",没有进入任何游戏,进入房间")
                return;
            }

            if (this.userList[_userId].getSeat() != -1) {
                log.info("用户" + _userId + "已经有座位");
                return;
            }

            this.userList[_userId].loginRoom(roomid);
            var LoginResult;
            var linemsg = this.getLineOutMsg(_userId);
            if (linemsg.Result) {
                log.info("断线重连接table:" + linemsg.tableId + " seatid:" + linemsg.seatId);
                LoginResult = this.sever.LoginRoombyLineOut(this.getUser(_userId), _socket, linemsg.tableId, linemsg.seatId);
                this.lineOutSet({state: 0, userId: _userId});
            } else {
                LoginResult = this.sever.LoginRoom(this.getUser(_userId), _socket);
            }
            //进入房间后，帮分配座位
            // LoginResult
            //发送场景消息给当前用户
            var tableUserList = Array();

            for (var i = 0; i < this.sever.seatMax; i++) {
                //除了自己以外
                //log.info(LoginResult.tableId);
                //log.info(this.sever.tableList);
                if (this.sever.tableList[LoginResult.tableId][i] && this.sever.tableList[LoginResult.tableId][i] != _userId) {
                    var userItem = {};
                    var userid = this.sever.tableList[LoginResult.tableId][i];

                    if (this.userList[userid]) {
                        //先确定在线才能拿到相关信息
                        userItem.userId = this.userList[userid].getUserId();
                        userItem.seatId = this.userList[userid].getSeat();
                        userItem.nickname = this.userList[userid]._nickname;
                        userItem.score = this.userList[userid]._score;
                        userItem.userType = this.userList[userid]._Robot;
                        var url = 0;
                        if (this.userList[userid]._headimgurl) {
                            //url = "bosengame.com/weixin/Login/img.aspx?url=" + urlencode(this.userList[userid]._headimgurl);
                            url = ""
                        }

                        userItem.headimgurl = url;
                        tableUserList.push(userItem);
                    }
                }
            }
            //发送场景消息
            //检查自己下注情况,效准玩家金额
            var self = this;
            gameDao.getFreeCount(_userId, function (ResultCode, Result) {
                //log.info("**" + Result.Id);
                if (!self.userList[_userId]) return;
                Result.Id = _userId
                self.userList[_userId].updateFreeGame(Result);
                log.info("从数据库里获得免费次数" + Result.freeCount);

                var ResultData = {
                    TableId: LoginResult.tableId,
                    seatId: LoginResult.seatId,
                    userList: tableUserList,
                    freeCount: self.userList[_userId].getFreeCount(),
                    score_pool: self.A.getVirtualScorePool()
                }
                _socket.emit("LoginRoomResult", {ResultCode: 1, ResultData: ResultData});

                if (!linemsg.Result) {
                    var tablestring = "table" + LoginResult.tableId;
                    var url = 0;
                    if (self.userList[_userId]._headimgurl) {
                        //url = "bosengame.com/weixin/Login/img.aspx?url=" + urlencode(self.userList[_userId]._headimgurl);
                        url = ""
                    }
                    _socket.broadcast.to(tablestring).emit('playEnter', {
                        ResultCode: 1,
                        ResultData: {
                            userId: _userId,
                            TableId: LoginResult.tableId,
                            seatId: LoginResult.seatId,
                            nickname: self.userList[_userId]._nickname,
                            score: self.userList[_userId]._score,
                            headimgurl: url,
                            userType: self.userList[_userId]._Robot
                        }
                    });
                }

            })

        }

        //登录获取免费次数
        this.LoginfreeCount = function (_userId, _socket) {
            var self = this;
            gameDao.getFreeCount(_userId, function (ResultCode, Result) {
                if (!self.userList[_userId]) return;
                Result.Id = _userId
                self.userList[_userId].updateFreeGame(Result);
                log.info("从数据库里获得免费次数" + Result.freeCount);
                _socket.emit("LoginfreeCountResult", {ResultCode: 1, freeCount: Result.freeCount});
            })
        };


        //断线保存
        this.lineOutSet = function (_info) {
            if (_info.state == 1) {
                //添加
                this.lineOutList[_info.userId] = {tableId: _info.tableId, seatId: _info.seatId}
                //log.info(this.lineOutList[_info.userId]);
            } else {
                //移除
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: _info.userId
                })
                delete this.lineOutList[_info.userId];
            }
        }

        //获得断线用户信息
        this.getLineOutMsg = function (_userId) {
            if (this.lineOutList[_userId]) {
                this.lineOutList[_userId].Result = 1;
                return this.lineOutList[_userId];
            } else {
                return {Result: 0};
            }
        }

        //清楚断线用户信息
        this.cleanLineOut = function () {
            //清理登录服务器
            log.info(this.lineOutList)
            for (var Item in this.lineOutList) {
                Item = parseInt(Item)
                var tableid = this.lineOutList[Item].tableId;
                var tablestring = "table" + tableid;
                this._io.sockets.in(tablestring).emit('PlayerOut', {
                    PlayerSeatId: this.lineOutList[Item].seatId,
                    userId: Item
                });
                this.sever.cleanLineOut(tableid, this.lineOutList[Item].seatId)
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: Item
                })
            }
            this.lineOutList = {};
        }

        this.getDownTime = function (_socket) {
            if (!this.userList[_socket.userId]) {
                //log.info("用户" + _socket.userId + "不存在");
                return;
            }

            var tableid = this.userList[_socket.userId].TableId;
            if (tableid < 0) {
                _socket.emit("getDownTimeResult", {ResultCode: 0, msg: "用户没有进入桌子"});
                return;
            }

            if (this.upUserList[tableid].length == 0) {
                _socket.emit("getDownTimeResult", {
                    ResultCode: 1,
                    downTime: this.sever.downTime,
                    upUserList: [],
                    upCoin: 0,
                    DownCoin: [0, 0, 0],
                    myDownCoin: [0, 0, 0]
                });
                return;
            }

            var down1 = 0;
            var down2 = 0;
            var down3 = 0;
            for (var itme in this.downCoinList[tableid]) {
                down1 += this.downCoinList[tableid][itme][0];
                down2 += this.downCoinList[tableid][itme][1];
                down3 += this.downCoinList[tableid][itme][2];
            }

            var mydown1 = 0;
            var mydown2 = 0;
            var mydown3 = 0;
            if (this.downCoinList[tableid][_socket.userId]) {
                mydown1 = this.downCoinList[tableid][_socket.userId][0];
                mydown2 = this.downCoinList[tableid][_socket.userId][1];
                mydown3 = this.downCoinList[tableid][_socket.userId][2];
            }

            //每门下注额度
            _socket.emit("getDownTimeResult", {
                ResultCode: 1,
                downTime: this.sever.downTime,
                upUserList: this.upUserList[tableid],
                upCoin: this.upUserList[tableid][0].upCoin,
                DownCoin: [down1, down2, down3],
                myDownCoin: [mydown1, mydown2, mydown3]
            });
        }


        this.disconnectAllUser = function () {
            for (var itme in this.userList) {
                this.userList[itme]._socket.disconnect();
            }
            log.info("服务器开启维护，已经全部离线");
        }

        //运行初始化
        this.init();
    }


    if (_gameinfo) {
        return {getInstand: _gameinfo}
    } else {
        log.info("####create game!####");
        _gameinfo = new Game();
        return {getInstand: _gameinfo}
    }

}()

function RandomNumBoth(Min, Max) {
    //生成指定范围内随机整数
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range); //四舍五入
    return num;
}


module.exports = GameInfo;


//监听gm发送来的消息
redis_send_and_listen.client_1.on("message", function (channel, message) {
    log.info("------------------------------server接收到信息了");
    log.info("channel" + channel);
    log.info("message" + message);
    var message = JSON.parse(message);
    if (channel == "EditLabaSet") {
        if (parseInt(message.serverId) == gameConfig.serverId) {
            if (parseInt(message.type) == 1) {    //修改水位
                GameInfo.getInstand.A.nGamblingWaterLevelGold = parseInt(message.swval);
                log.info("修改水位", GameInfo.getInstand.A.nGamblingWaterLevelGold)
            }
            if (parseInt(message.type) == 2) {    //修改难度
                GameInfo.getInstand.A.nGamblingBigWinLevel = message.BigWinlevel.split(',').map(Number);  //大奖幸运等级
                GameInfo.getInstand.A.nGamblingBigWinLuck = message.BigWinluck.split(',').map(Number);    //大奖幸运概率
                log.info("修改难度等级", GameInfo.getInstand.A.nGamblingBigWinLevel)
                log.info("修改难度幸运", GameInfo.getInstand.A.nGamblingBigWinLuck)
            }

        }
    }

});

